package miage.rest.db.bean;

import java.beans.PropertyDescriptor;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Arrays;

/**
 * 
 * Ce BeanProcessor permet de convertir les colonnes utilisant la notation
 * avec des underscore ("_") vers une notation "Camel Case".
 *
 * @author Schwartz Michaël
 *
 */
public class BeanProcessor extends org.apache.commons.dbutils.BeanProcessor {

	@Override
	protected int[] mapColumnsToProperties(ResultSetMetaData rsmd, PropertyDescriptor[] props) throws SQLException {
			
		  	int cols = rsmd.getColumnCount();
	        int columnToProperty[] = new int[cols + 1];
	        Arrays.fill(columnToProperty, PROPERTY_NOT_FOUND);

			for (int propIndex = 0 ; propIndex < props.length ; propIndex++) {

				String propName = props[propIndex].getName();
				for (int col = 1; col <= cols; col++) {
					String columnName = this.convertToCamelCase(rsmd.getColumnName(col));
					if (columnName.equalsIgnoreCase(propName)) {
						columnToProperty[col] = propIndex;
						break;
					}
				}
			}

	        return columnToProperty;

	}

        /**
         * Permet de caster les noms de colonnes
         * @param cn
         * @return
         */
	private String convertToCamelCase(String cn) {
		StringBuffer sb = new StringBuffer();
		String[] str = cn.split("_");
		boolean firstTime = true;
		for(String temp : str) {
			if(firstTime) {
				sb.append     (temp.toLowerCase());
				firstTime = false;
			} else {
				sb.append(Character.toUpperCase(temp.charAt(0)));
				sb.append(temp.substring(1).toLowerCase());
			}
		}
        return sb.toString();
	}

}
